package com.cubeofnine.sugar;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils.TruncateAt;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout.LayoutParams;
import android.widget.TextView;

import com.cubeofnine.sugar.business.ContactsBusiness;
import com.cubeofnine.sugar.inf.FunctionHandlerInterface;
import com.cubeofnine.sugar.inf.HeaderFunctionGroupInterface;
import com.cubeofnine.sugar.service.element.EntryListResult;
import com.cubeofnine.sugar.service.element.EntryValue;
import com.cubeofnine.sugar.service.element.NameValue;
import com.cubeofnine.utils.ActivityParams;
import com.cubeofnine.utils.ScrollingTextView;
import com.cubeofnine.utils.StringUtils;

public class FunctionContactsActivity extends ActivityImpt implements
		HeaderFunctionGroupInterface, FunctionHandlerInterface {

	private static ContactsBusiness contactsBusiness = null;
	private static EntryListResult entryListResult = null;
	private static EditText searchText = null;
	private static int offset = 0;
	private static int rowPerLoad = 20;
	private static LinearLayout contentLoadMore;

	// Thread and Handler Variables
	private static Handler handler;
	private Thread thread;

	private static Context context = null;

	public String getClassName() {
		return FunctionContactsActivity.class.getName();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.i(getClassName(), "onCreate() : Start");

		super.onCreate(savedInstanceState);
		setContentView(R.layout.function_contacts);

		context = this;

		TextView headerTitle = (TextView) findViewById(R.id.header_title);
		headerTitle.setText(R.string.function_contacts);

		searchText = (EditText) findViewById(R.id.text_search);

		try {
			boolean isOnline = isOnline();

			Log.d(getClassName(), "isOnline = " + isOnline);
			if (isOnline) {
				// Create a handler to update the UI
				handler = new Handler();

				// Check if the thread is already running
				thread = (Thread) getLastNonConfigurationInstance();
				if (thread != null && thread.isAlive()) {
					initProgressDialog(null);
				} else {
					offset = 0;
					doClickContacts();
				}
			} else {
				alertDialog(R.string.msg_no_connection);
			}
		} catch (Exception e) {
			Log.e(getClassName(), "onCreate()", e);
			alertDialog(R.string.msg_application_error);
		}

		Log.i(getClassName(), "onCreate() : End");
	}

	public void onDestroy() {
		Log.i(getClassName(), "onDestroy() : Start");

		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
			dialog = null;
		}

		Log.i(getClassName(), "onDestroy() : End");
		super.onDestroy();
	}

	// Save the thread
	@Override
	public Object onRetainNonConfigurationInstance() {
		Log.d(getClassName(), "onRetainNonConfigurationInstance()");
		return thread;
	}

	static public class FunctionContactsActivityThread extends Thread {
		public static String getClassName() {
			return FunctionContactsActivityThread.class.getName();
		}

		@Override
		public void run() {
			Log.i(getClassName(), "run() : Start");

			try {
				errorMessage = null;
				String searchBy = searchText.getText().toString().trim()
						.toLowerCase();
				searchBy = StringUtils.encodeToken(searchBy);

				contactsBusiness = new ContactsBusiness(context);
				
				// entryListResult = contactsBusiness.getEntryList(searchBy,
				// ContactsBusiness.CONTACTS_ORDER_BY_DEFAULT, offset,
				// null, rowPerLoad, 0);
				
				entryListResult = contactsBusiness.getContactList(searchBy,
						"first_name, last_name, account_name, title", offset,
						rowPerLoad);
			} catch (Exception e) {
				Log.e(getClassName(), "Connection Error", e);
				errorMessage = context.getString(R.string.msg_connection_error);
			} finally {
				Log.d(getClassName(), "Finally");
				handler.post(new FunctionContactsActivityRunnable());
			}

			Log.i(getClassName(), "run() : End");
		}

	}

	static public class FunctionContactsActivityRunnable implements Runnable {
		public static String getClassName() {
			return FunctionContactsActivityRunnable.class.getName();
		}

		public void run() {
			Log.i(getClassName(), "run() : Start");
			Log.d(getClassName(), "errorMessage = " + errorMessage);

			if (errorMessage != null && !"".equals(errorMessage.trim())) {
				((ActivityImpt) context).alertDialog(errorMessage);
			} else {
				((FunctionContactsActivity) context).genContent();
			}

			dialog.dismiss();

			Log.i(getClassName(), "run() : End");
		}
	}

	public void doClickContacts() {
		Log.i(getClassName(), "doClickContacts() : Start");

		initProgressDialog(null);

		thread = new FunctionContactsActivityThread();
		thread.start();

		Log.i(getClassName(), "doClickContacts() : End");
	}

	public void doClickContactsIcon(View view) {
		Log.i(getClassName(), "doClickContacts() : Start");

		ImageView imageView = (ImageView) findViewById(view.getId());

		List<ActivityParams> params = new Vector<ActivityParams>();
		params.add(new ActivityParams(ContentDetailActivity.MODULE_NAME,
				ContactsBusiness.MODULE_CONTACTS));
		params.add(new ActivityParams(ContentDetailActivity.MODULE_ID,
				imageView.getContentDescription().toString()));
		gotoActivity(ContentDetailActivity.class, params);

		Log.i(getClassName(), "doClickContacts() : End");
	}

	public void doClickAccount(View view) {
		Log.i(getClassName(), "doClickAccount() : Start");

		List<ActivityParams> params = new Vector<ActivityParams>();
		params.add(new ActivityParams(ContentDetailActivity.MODULE_NAME,
				ContactsBusiness.MODULE_ACCOUNTS));
		params.add(new ActivityParams(ContentDetailActivity.MODULE_ID,
				((TextView) view).getContentDescription().toString()));
		gotoActivity(ContentDetailActivity.class, params);

		Log.i(getClassName(), "doClickAccount() : End");
	}

	public void genContent() {
		LinearLayout root = (LinearLayout) findViewById(R.id.body_root_linear_layout);

		if (entryListResult != null) {
			if (offset == 0) {
				root.removeAllViewsInLayout();
			} else {
				if (contentLoadMore != null) {
					root.removeViewInLayout(contentLoadMore);
				}
			}

			offset = entryListResult.getNextOffset();
			int resultCount = entryListResult.getResultCount();

			Log.d(getClassName(), "offset = " + offset);
			Log.d(getClassName(), "resultCount = " + resultCount);

			if (resultCount > 0) {
				LinearLayout contactRoot = null;
				ImageView contactIcon = null;
				LinearLayout messageLayout = null;
				ScrollingTextView contactName = null;
				ScrollingTextView contactTitle = null;
				ScrollingTextView contactCompany = null;
				Button loadMoreBtn = null;

				// Contact Root Layout
				LinearLayout.LayoutParams contactRootParams = new LinearLayout.LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);// W,H
				contactRootParams.setMargins(10, 2, 10, 2);// left, top, right,
															// bottom

				LinearLayout.LayoutParams messageLayOutParams = new LinearLayout.LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);// W,H
				messageLayOutParams.setMargins(10, 0, 0, 0);// left, top,
															// right, bottom

				LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
				textParams.setMargins(0, 2, 0, 2);

				String id = "";
				String salutation = "";
				String firstName = "";
				String lastName = "";
				String title = "";
				String accountsId = "";
				String accountsName = "";
				EntryValue entry = null;

				int i = 1;
				Map entryList = entryListResult.getEntryList();
				Set entrySet = entryList.keySet();
				Iterator entryIter = entrySet.iterator();

				int offsetIndex = (offset - resultCount) + 1;
				while (entryIter.hasNext()) {
					accountsId = "";
					accountsName = "";

					entry = (EntryValue) entryList.get(((String) entryIter
							.next()));
					id = entry.getId();

					// Iterator iter = entry.getNameValueList().keySet()
					// .iterator();
					// while (iter.hasNext()) {
					// Log.d(getClassName(),
					// "Key = " + String.valueOf(iter.next()));
					// }

					salutation = ((NameValue) entry.getNameValueList().get(
							"salutation")).getValue();
					firstName = ((NameValue) entry.getNameValueList().get(
							"first_name")).getValue();
					lastName = ((NameValue) entry.getNameValueList().get(
							"last_name")).getValue();
					title = ((NameValue) entry.getNameValueList().get("title"))
							.getValue();
					
					try {
						accountsId = ((NameValue) entry.getNameValueList().get(
								"account_id")).getValue();
						accountsName = ((NameValue) entry.getNameValueList()
								.get("account_name")).getValue();
					} catch (Exception e) {
						Log.e(getClassName(), "ID = " + id, e);
					}

					firstName = (salutation + " " + firstName + " " + lastName)
							.trim();

					contactRoot = new LinearLayout(this);
					contactRoot.setLayoutParams(contactRootParams);
					contactRoot.setOrientation(LinearLayout.HORIZONTAL);

					// Contact Image
					contactIcon = new ImageView(this);
					contactIcon.setId(i++);
					contactIcon.setContentDescription(id);
					contactIcon.setImageResource(R.drawable.ic_card_id);
					contactIcon.setLayoutParams(new ViewGroup.LayoutParams(65,
							65));// W,H
					contactIcon.setScaleType(ImageView.ScaleType.FIT_CENTER);
					contactIcon.setOnClickListener(new OnClickListener() {
						public void onClick(View view) {
							view.startAnimation(AnimationUtils.loadAnimation(
									context, R.anim.image_click));
							// TODO Auto-generated method stub
							doClickContactsIcon(view);
						}
					});

					// Text Layout

					messageLayout = new LinearLayout(this);
					messageLayout.setLayoutParams(messageLayOutParams);
					messageLayout.setOrientation(LinearLayout.VERTICAL);
					messageLayout.setGravity(Gravity.CENTER);

					// Contact Name
					contactName = new ScrollingTextView(this);
					contactName.setLayoutParams(textParams);
					contactName.setText(offsetIndex++ + ".) " + firstName);
					contactName.setTextColor(Color.rgb(0, 102, 255));// Blue
					contactName.setTextAppearance(this,
							android.R.attr.textAppearanceLarge);
					contactName.setSingleLine(true);
					contactName.setHorizontallyScrolling(true);
					contactName.setEllipsize(TruncateAt.MARQUEE);
					contactName.setMarqueeRepeatLimit(1);
					contactName
							.setMovementMethod(new ScrollingMovementMethod());
					messageLayout.addView(contactName);

					// Title Name
					contactTitle = new ScrollingTextView(this);
					contactTitle.setLayoutParams(textParams);
					contactTitle.setText(title);
					contactTitle.setTextColor(Color.rgb(170, 170, 170));// Gray
					contactTitle.setTextAppearance(this,
							android.R.attr.textAppearanceSmall);
					contactTitle.setSingleLine(true);
					contactTitle.setHorizontallyScrolling(true);
					contactTitle.setEllipsize(TruncateAt.MARQUEE);
					contactTitle.setMarqueeRepeatLimit(1);
					contactTitle
							.setMovementMethod(new ScrollingMovementMethod());
					messageLayout.addView(contactTitle);

					// Company
					contactCompany = new ScrollingTextView(this);
					contactCompany.setLayoutParams(textParams);
					contactCompany.setText(accountsName);
					contactCompany.setTextColor(Color.rgb(170, 170, 170));// Gray
					contactCompany.setTextAppearance(this,
							android.R.attr.textAppearanceSmall);
					contactCompany.setSingleLine(true);
					contactCompany.setHorizontallyScrolling(true);
					contactCompany.setEllipsize(TruncateAt.MARQUEE);
					contactCompany.setMarqueeRepeatLimit(1);
					contactCompany
							.setMovementMethod(new ScrollingMovementMethod());
					if (accountsId != null && !accountsId.isEmpty()) {
						contactCompany.setClickable(true);
						contactCompany.setContentDescription(accountsId);
						contactCompany
								.setOnClickListener(new OnClickListener() {
									public void onClick(View view) {
										// TODO Auto-generated method stub
										doClickAccount(view);
									}
								});
					}
					messageLayout.addView(contactCompany);

					contactRoot.addView(contactIcon);
					contactRoot.addView(messageLayout);
					root.addView(contactRoot);
				}

				if (resultCount == rowPerLoad) {
					contentLoadMore = new LinearLayout(this);
					contentLoadMore.setLayoutParams(contactRootParams);
					contentLoadMore.setOrientation(LinearLayout.VERTICAL);

					loadMoreBtn = new Button(this);
					loadMoreBtn
							.setLayoutParams(new LinearLayout.LayoutParams(
									LayoutParams.FILL_PARENT,
									LayoutParams.WRAP_CONTENT));// W,H
					loadMoreBtn.setText(R.string.button_load_more);
					loadMoreBtn.setGravity(Gravity.CENTER);
					loadMoreBtn.setOnClickListener(new OnClickListener() {
						public void onClick(View view) {
							// TODO Auto-generated method stub
							((Button) view).setEnabled(false);
							doClickContacts();
						}
					});
					contentLoadMore.addView(loadMoreBtn);
					root.addView(contentLoadMore);
				}
			}
		}
	}

	public void onClickAccountsFunction(View view) {
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));
		// TODO Auto-generated method stub
		gotoActivity(FunctionAccountsActivity.class);
	}

	public void onClickContactsFunction(View view) {
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));
		// TODO Auto-generated method stub
		searchText.setText("");
		offset = 0;
		doClickContacts();
	}

	public void onClickOpportunitiesFunction(View view) {
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));
		// TODO Auto-generated method stub

	}

	public void onClickLeadsFunction(View view) {
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));
		// TODO Auto-generated method stub

	}

	public void onClickCampaignsFunction(View view) {
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));
		// TODO Auto-generated method stub

	}

	public void onClickTargetsFunction(View view) {
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));
		// TODO Auto-generated method stub

	}

	public void onClickCasesFunction(View view) {
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));
		// TODO Auto-generated method stub

	}

	public void onClickReloadButton(View view) {
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));
		// TODO Auto-generated method stub
		// searchText.setText("");
		offset = 0;
		doClickContacts();
	}

	public void onClickOptionalButton(View view) {
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));
		// TODO Auto-generated method stub
		gotoActivity(FunctionContactsAddActivity.class);
	}

	public void onClickSearchButton(View view) {
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));
		// TODO Auto-generated method stub
		offset = 0;
		doClickContacts();
	}
}
